import fs from "fs";
import fse from "fs-extra";
import { getTemplatesDirRootPath } from "../utils/index.js";
import { runCmdSync } from "./runCmd.js";

// 存放模板文件的目录路径
const templatesDirRootPath = getTemplatesDirRootPath();
const remoteUrl =
  "https://gitee.com/yanhuakang/create-package-tools-template.git";
// 获取远程仓库目录名称
const getGitRemoteFilename = () => {
  const arr = remoteUrl.split("/");
  return arr[arr.length - 1].split(".")[0];
};
const gitRemoteFilename = getGitRemoteFilename();

// 根据 open api 读取远程仓库内容，并写入本地
const cloneGitRemoteFileAndWrite = (createConfig) => {
  return new Promise(async (resolve, reject) => {
    // project 是否已经存在于本地
    // const projectExist = fs.existsSync(`./${createConfig.projectName}`);
    // if (projectExist) {
    //   fs.rmSync(`./${createConfig.projectName}`, {
    //     maxRetries: 3,
    //     recursive: true,
    //   });
    // }

    // 先创建文件夹
    fs.mkdirSync(createConfig.projectName, { recursive: true });

    // 该远程仓库是否已经存在于本地
    const exist = fs.existsSync(templatesDirRootPath);
    if (exist) {
      fs.rmSync(templatesDirRootPath, { maxRetries: 3, recursive: true });
    }
    fs.mkdirSync(templatesDirRootPath, { recursive: true });

    try {
      runCmdSync(`git`, ["clone", "-b", "master", remoteUrl], {
        cwd: templatesDirRootPath,
      });

      // 写入 .gitignore
      const gitignore = fs.readFileSync(
        `${templatesDirRootPath}/${gitRemoteFilename}/.gitignore`,
        "utf8"
      );
      fs.writeFileSync(
        `./${createConfig.projectName}/.gitignore`,
        gitignore,
        "utf8"
      );

      // 写入 .commitlint.config.js
      const commitlintConfig = fs.readFileSync(
        `${templatesDirRootPath}/${gitRemoteFilename}/commitlint.config.js`,
        "utf8"
      );
      fs.writeFileSync(
        `./${createConfig.projectName}/commitlint.config.js`,
        commitlintConfig,
        "utf8"
      );

      // 写入 .prettierrc.js
      const prettierrcJs = fs.readFileSync(
        `${templatesDirRootPath}/${gitRemoteFilename}/.prettierrc.js`,
        "utf8"
      );
      fs.writeFileSync(
        `./${createConfig.projectName}/.prettierrc.js`,
        prettierrcJs,
        "utf8"
      );

      await fse.copy(
        `${templatesDirRootPath}/${gitRemoteFilename}/${createConfig.framework}`,
        `./${createConfig.projectName}`
      );

      resolve();
      fs.rmSync(templatesDirRootPath, { maxRetries: 3, recursive: true });
    } catch (err) {
      console.error(err);
      reject(err);
    }
  });
};

export default cloneGitRemoteFileAndWrite;
